$(document).ready(function(){
    // Define URL
    var FAVORITE_URL      = TWEET_API_URL + "favorite";
    var UNFAVORITE_URL    = TWEET_API_URL + "unfavorite";
    var RETWEET_URL       = TWEET_API_URL + "retweet";
    var UNRETWEET_URL     = TWEET_API_URL + "unretweet";
    var DEL_URL           = TWEET_API_URL + "destroy";
    var POST_URL          = TWEET_API_URL + "post";
    var EXPAND_URL        = TWEET_API_URL + "tweetExpand";
    
    // Sample Data
    var Tweet = Backbone.Model.extend({

    });

    var Tweets = Backbone.Collection.extend({
        since_id : 0,
        max_id   : 0,
        url : function(){
          return GET_TWEET_URL + "?since_id="+ this.since_id;
        },
        model : Tweet
    });

    var TweetView = Backbone.View.extend({
        className  : "js-stream-items stream-items",
        template   : $("#tweetTemplate").html(),
        events: {
            "click .action-fav-container"     : "favAction",
            "click .action-rt-container"      : "rtAction",
            "click .action-del-container"     : "delAction",
            "click .action-reply-container"   : "replyAction",
            "click .expand-stream-item"       : "expandAction",
            "click .collapse-stream-item"     : "collapseAction",
            
            "click .expand-action-wrapper"    : "expandAction",
            "click .collapse-action-wrapper"  : "collapseAction"
        },
        initialize : function(){
            this.model.on("add", this.render, this);
        },
        render    : function(){
            var tmpl = _.template(this.template);
            this.$el.html(tmpl(this.model.toJSON()));
            this.$el.find("._timestamp").timeago();
            return this;
        },
        
        // tweet Action
        favAction : function(e){
            e.preventDefault();
            
            var refav      = parseInt(this.model.get("refav"));
            var requestURL = FAVORITE_URL;
            if (refav/10 < 1)
                this.model.set({refav : (refav +10) + ""});
            else{
                this.model.set({refav : (refav -10) + ""});
                requestURL = UNFAVORITE_URL;
            }
            
            // Send request
            $.ajax({
                url: requestURL,
                data: { tweet_id: this.model.get("tweet_id") }
            }).done(function() { 
            });
            
            this.render();
        },
        rtAction : function(e){
            e.preventDefault();
            if (currentUserID == this.model.get("user_id"))
                return;
            
            var refav      = parseInt(this.model.get("refav"));
            var requestURL = RETWEET_URL;
            if (refav%10 == 0)
                this.model.set({refav : (refav +1) + ""});
            else{
                this.model.set({refav : (refav -1) + ""});
                requestURL = UNRETWEET_URL;
            }
            
            // Send request
            $.ajax({
                url: requestURL,
                data: { tweet_id: this.model.get("tweet_id") }
            }).done(function() { 
            });
            
            this.render();
        },
        delAction : function(e){
            e.preventDefault();
            var that = this;
            bootbox.dialog("Are you sure you want to delete this tweet?", [{
                    "label" : "No",
                    "class" : "btn-success",
                    "icon"  : "icon-ok-sign icon-white"
                }, {
                    "label" : "Yes",
                    "class" : "btn-danger",
                    "icon"  : "icon-warning-sign icon-white",
                    "callback" : function(){
                        that.$el.fadeOut('slow',function(){
                            $.ajax({
                                url: DEL_URL,
                                data: { tweet_id: that.model.get("tweet_id") }
                            }).done(function() { 
                            });
                            that.model.destroy();
                            that.remove();
                        });
                    }
                }]);
        },
        replyAction : function(e){
            e.preventDefault();
            
            var postView = new PostView({model: this.model});
            bootbox.modal(postView.render().$el, 'Reply to @'+this.model.get("username"));
            $(".post-content").focus();
            $(".post-content").val("");
        },
        
        expandAction : function(e){
            e.preventDefault();
            
            // Get data from server
            that = this;
            $.ajax({
                url: EXPAND_URL,
                data: { tweet_id: that.model.get("tweet_id") }
            }).done(function(res) { 
                res = $.parseJSON(res);
                that.model.set("more",res);
                that.template = $("#tweetTemplateExpanded").html();
                that.render();
            });
        },
        collapseAction : function(e){
            e.preventDefault();
            
            this.template = $("#tweetTemplate").html(),
            this.render();
        }
    });

    var MasterView = Backbone.View.extend({
        el : "#stream-items-id",
        
        // Define events
        events : {
        },

        initialize : function(){
            this.collection = new Tweets(tweetList);
            var coll = this.collection;
            if (coll.length > 0){
                coll.max_id   = coll.at(0).get("tweet_id");
                coll.since_id = coll.at(this.collection.length - 1).get("tweet_id");
            }
            this.setLoading(false);
            
            // Add event listener
            _.bindAll(this, 'checkScroll');
            $(window).scroll(this.checkScroll);
            this.collection.on("add", this.addTweet, this);
            this.render();
        },
        
        setLoading : function(loading){
            this.isLoading = loading;
            if (loading){
                $(".stream-loading").hide();
            }
            else
                $(".stream-loading").hide();
        },

        render : function(){
            var that = this;
            _.each(this.collection.models, function(item){
                that.renderTweet(item);
            })
        },
        addTweet : function(item){
            if (item.get("order_id") < this.collection.since_id){
                this.collection.since_id = item.get("tweet_id");
                this.renderTweet(item);
            }
            else{
                this.collection.max_id = item.get("tweet_id");
                this.renderTweetBefore(item);
            }
        },
        renderTweet : function(item){
            var tweetView = new TweetView({model : item});
            this.$el.append(tweetView.render().el);
        },
        renderTweetBefore : function(item){
            var tweetView = new TweetView({model : item});
            this.$el.prepend(tweetView.render().el);
        },
        getNew : function(){
            that = this;
            $.ajax({
                url: GET_TWEET_URL,
                data: { max_id: that.collection.max_id}
            }).done(function(res) { 
                res = $.parseJSON(res);
                that.collection.add(res);
            });
        },
        autoRefresh : function(){
            this.getNew();
            //setTimeout("masterView.autoRefresh()", 10000);
        },
        checkScroll : function() {
            if  ($(window).scrollTop() > this.$el.children().last().position().top - $(window).height()){
                console.log("Need load more");
                var that = this;
                this.setLoading(true);
                this.collection.fetch({
                   success: function(tweets){
                       that.setLoading(false);
                       that.collection.add(tweets.toJSON());
                   }
                });
            }
        }
    });
    
    masterView = new MasterView();
    masterView.autoRefresh();
    Backbone.emulateHTTP = true;
    Backbone.emulateJSON = true;
    
});

// Ultity function

function processContent(tweet_content){
   // pretty url link
   
   links = tweet_content.match(/http:\/\/\S*jpg\b/g);
   for (i in links){
       link = links[i];
       newLink = genLink(link);
       tweet_content = tweet_content.replace(link, newLink);
   }
   
   // pretty mentions link
   mentions = tweet_content.match(/@\w*\b/g);
   for (i in mentions){
       mention = mentions[i];
       username = mention.substr(1);
       mentionLink = genMentionLink(username);
       tweet_content = tweet_content.replace(mention, mentionLink);
   }
   return tweet_content;
}

function genMentionLink(username){
    return '<a class="twitter-atreply pretty-link" href="/user/'+username+'" data-screen-name="'+username+'"><s>@</s><b>'+username+'</b></a>';
}

function genLink (link){
    return '<a rel="nofollow" target="_blank" class="twitter-timeline-link" title="'+link+'" href="'+link+'">'+link+'</a>';
}